package com.factory.rest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.factory.common.bean.User;
import com.factory.common.bean.UserDevices;
import com.factory.common.core.SqlCondition;
import com.factory.common.pojo.QueryListParam;
import com.factory.common.pojo.Result;
import com.factory.common.pojo.SendData;
import com.factory.common.utils.StringUtil;
import com.factory.rest.feign.AiClients;
import com.factory.rest.feign.BaseFeignClient;
import com.factory.rest.feign.CameraClient;
import com.factory.rest.pojo.CameraPojo;
import com.factory.rest.service.UserDevicesService;
import com.factory.rest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 摄像头数据类
 *
 * @author JW
 * @version 1.0
 * @date 2020/11/17 15:01
 */
@RestController
@RequestMapping("/rest/camera")
public class CameraController extends BaseFeignController<CameraPojo>{

    @Autowired
    private  CameraClient cameraClient;

    @Override
    protected BaseFeignClient getBaseFeignClient() {
        return cameraClient;
    }

    @Autowired
    private UserService userService;

    @Autowired
    private AiClients aiClients;

    @Autowired
    private UserDevicesService userDevicesService;

    /**
     * 设备数据统计
     *
     * @return
     */
    @RequestMapping("/statistics")
    public Result statistics() {
        log.info("设备数据统计");
        User user = userService.getLoginUser().get();
        var params = new HashMap<String,Object>();
        params.put("userId",user.getId());
        return cameraClient.statistics(params);
    }

    @Override
    public Result insert(@RequestBody CameraPojo cameraPojo) {
        log.info("添加摄像头数据,{}",cameraPojo);
        Optional<Result> result = cameraPojo.vInsert();
        if(result.isPresent()){
            return result.get();
        }

        Result onLine = aiClients.isOnLine(cameraPojo.getDeviceId());
        if(!onLine.isStatus() || !Boolean.valueOf(StringUtil.val(onLine.getData(),"false"))){
            return Result.fail("设备不在线无法添加数据!");
        }

        User user = userService.getLoginUser().get();
        cameraPojo.setId(StringUtil.getUUID());
        cameraPojo.setUserId(user.getId());
        cameraPojo.setUserName(user.getName());

        UserDevices userDevices = userDevicesService.selectById(cameraPojo.getDeviceId());

        cameraPojo.setLocationId(userDevices.getLocationId());
        cameraPojo.setLocationName(userDevices.getLocationName());
        cameraPojo.setDeviceName(userDevices.getName());

        cameraPojo.setCreateDate(new Date());
        cameraPojo.setStatus(1);

        Result insert = cameraClient.insert(cameraPojo);
        if(!insert.isStatus()){
            return insert;
        }

        //调用aiclient添加数据
        SendData sendData = new SendData();
        sendData.setMethod("insertCamera");
        sendData.setId(cameraPojo.getDeviceId());
        sendData.setData(JSON.parseObject(JSON.toJSONString(cameraPojo)));
        Result seedClient = aiClients.sendClient(sendData);

        //失败删除数据
        if(!seedClient.isStatus()){
            cameraClient.delete(cameraPojo.getId(),cameraPojo.getDeviceId());
        }

        return seedClient;
    }

    @Override
    Result update(@RequestBody CameraPojo cameraPojo, @PathVariable(name = "id") String id, @PathVariable(name = "deviceId") String deviceId) {
        log.info("修改摄像头数据,{}",cameraPojo);
        Optional<Result> result = cameraPojo.vUpdate();

        if(result.isPresent()){
            return result.get();
        }else if(StringUtil.isEmpty(id) || StringUtil.isEmpty(deviceId)){
            return Result.fail("id或deviceId不能为空!");
        }

        Result onLine = aiClients.isOnLine(deviceId);
        if(!onLine.isStatus() || !Boolean.valueOf(StringUtil.val(onLine.getData(),"false"))){
            return Result.fail("设备不在线无法修改数据!");
        }

        Result insert = cameraClient.update(cameraPojo,id,deviceId);
        if(!insert.isStatus()){
            return insert;
        }

        //调用aiclient添加数据
        SendData sendData = new SendData();
        sendData.setMethod("updateCamera");
        sendData.setId(deviceId);

        cameraPojo.setDeviceId(deviceId);
        cameraPojo.setId(id);
        sendData.setData(JSON.parseObject(JSON.toJSONString(cameraPojo)));
        Result seedClient = aiClients.sendClient(sendData);

        //失败删除数据
        if(seedClient.isStatus()){
            cameraClient.update(cameraPojo,cameraPojo.getId(),cameraPojo.getDeviceId());
        }

        return seedClient;
    }

    /**
     * 改变播放质量
     * @return
     */
    @GetMapping("/quality/{deviceId}/{cameraId}/{quality}")
    public Result quality(@PathVariable(name = "deviceId") String deviceId, @PathVariable(name = "cameraId") String cameraId,@PathVariable(name = "quality") Integer quality){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("quality",quality);
        jsonObject.put("id",cameraId);
        return aiClients.sendClient(new SendData(deviceId,StringUtil.getUUID(),"set_quality", jsonObject));
    }

    /**
     * 查询告警信息接口
     *
     * @param param
     * @return
     */
    @Override
    public Result queryList(@RequestBody QueryListParam param) {
        log.info("查询告警信息接口,{}", param);

        User user = userService.getLoginUser().get();

        List<SqlCondition> conditions = param.getConditions();
        conditions.add(new SqlCondition("userId", user.getId(), SqlCondition.Conditions.EQ));
        conditions.add(new SqlCondition("createDate", "createDate", SqlCondition.Conditions.DESC));

        return cameraClient.queryList(param);
    }
}
